import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/model/user/user_address_model.dart';
import 'package:labcloud_app/model/user/user_cart_model.dart';
import 'package:labcloud_app/data/product.dart';
import 'package:labcloud_app/data/user_address.dart';
import 'package:labcloud_app/data/user_cart.dart';
import 'package:labcloud_app/api/graphql/order_gql.dart';
import 'package:labcloud_app/widget/async_image.dart';

import 'package:labcloud_app/data/order.dart' as order_data;

class OrderSubmitPage extends StatefulWidget {
  const OrderSubmitPage({super.key});

  @override
  State<OrderSubmitPage> createState() => _OrderSubmitPageState();
}

class _OrderSubmitPageState extends State<OrderSubmitPage> {
  Product? _product;
  List<UserCartItems> _cartItems = [];
  Map<int, Product> _products = {};
  int _quantity = 1;
  double _totalPrice = 0.0;
  UserAddress? _selectedAddress;
  String _paymentMethod = 'wallet'; // 默认使用钱包支付
  final TextEditingController _remarkController = TextEditingController();
  bool _isLoading = false;
  String _errorMessage = '';
  String? _payPassword;
  bool _isCreatingOrder = false;
  bool _isLoadAddressesCalled = false;

  @override
  void initState() {
    super.initState();
    _isLoading = true;
    _errorMessage = '';
    _loadProductFromArgs();
  }

  void _loadProductFromArgs() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final args = ModalRoute.of(context)?.settings.arguments;
      if (args is Map) {
        // 检查是否是来自购物车的参数
        if (args.containsKey('cartItems')) {
          // 处理来自购物车的多个商品
          final cartItems = args['cartItems'] as List<dynamic>;
          
          // 获取products映射（如果存在）
          final Map<int, Product>? products = args['products'] is Map<int, Product> 
              ? args['products'] as Map<int, Product> 
              : null;
          
          // 构建products映射（如果未提供）
          final Map<int, Product> finalProducts = Map<int, Product>.from(products ?? {});
          double totalPrice = 0.0;
          
          // 如果没有提供products映射，则从cartItems构建
          if (finalProducts.isEmpty) {
            for (final item in cartItems) {
              if (item is UserCart && item.product != null && item.productId != null) {
                final productId = int.tryParse(item.productId!);
                if (productId != null) {
                  finalProducts[productId] = item.product!;
                  
                  // 计算总价
                  final quantity = item.quantity?.toInt() ?? 1;
                  final price = double.tryParse(item.product!.price ?? '0') ?? 0.0;
                  totalPrice += price * quantity;
                }
              }
            }
          } else {
            // 如果提供了products映射，则从products计算总价
            for (final item in cartItems) {
              if (item is UserCart && item.productId != null) {
                final productId = int.tryParse(item.productId!);
                if (productId != null && finalProducts.containsKey(productId)) {
                  final product = finalProducts[productId]!;
                  final quantity = item.quantity?.toInt() ?? 1;
                  final price = double.tryParse(product.price ?? '0') ?? 0.0;
                  totalPrice += price * quantity;
                }
              }
            }
          }
          
          // 获取所有购物车商品
          setState(() {
            _cartItems = cartItems
              .whereType<UserCart>()
              .map((item) => UserCartItems(
                id: item.id,
                userId: item.userId,
                productId: item.productId,
                quantity: item.quantity,
                createTime: item.createTime,
                updateTime: item.updateTime,
              ))
              .toList();
            _products = finalProducts;
            _totalPrice = totalPrice;
            _isLoading = false;
          });
        } 
        // 检查是否是来自商品详情页的productId参数
        else if (args.containsKey('productId')) {
          // 处理来自商品详情页的单个商品ID
          final productId = args['productId'] as String?;
          final quantity = args['quantity'] as int? ?? 1;
          
          if (productId != null) {
            // 我们需要通过GraphQL查询获取商品详细信息
            _loadProductById(productId, quantity);
          } else {
            setState(() {
              _errorMessage = '商品ID不能为空';
              _isLoading = false;
            });
          }
        }
        // 检查是否是直接传递product对象
        else if (args.containsKey('product')) {
          // 处理来自商品详情页的单个商品
          setState(() {
            _product = args['product'] as Product?;
            _quantity = args['quantity'] as int? ?? 1;
            
            // 计算总价
            final price = double.tryParse(_product?.price ?? '0') ?? 0.0;
            _totalPrice = price * _quantity;
            _isLoading = false;
          });
        }
        else {
          setState(() {
            _errorMessage = '无效的参数';
            _isLoading = false;
          });
        }
      } else {
        setState(() {
          _errorMessage = '参数格式错误';
          _isLoading = false;
        });
      }
    });
  }

  Future<void> _loadProductById(String productId, int quantity) async {
    setState(() {
      _isLoading = true;
      _errorMessage = '';
    });
    
    try {
      final client = GraphQLProvider.of(context).value;
      
      final result = await client.query(
        QueryOptions(
          document: gql(r'''
            query GetProduct($id: Int!) {
              product {
                productById(id: $id) {
                  id
                  title
                  description
                  price
                  stockpile
                  rate
                  coverAddr
                  detailAddr
                  specificationList {
                    item
                    value
                  }
                }
              }
            }
          '''),
          variables: {
            'id': productId,
          },
        ),
      );

      if (result.hasException) {
        setState(() {
          _errorMessage = '加载商品信息失败: ${result.exception.toString()}';
          _isLoading = false;
        });
        return;
      }

      final productData = result.data?['product']?['productById'];
      if (productData != null) {
        final product = Product.fromJson(productData);
        setState(() {
          _product = product;
          _quantity = quantity;
          
          // 计算总价
          final price = double.tryParse(product.price ?? '0') ?? 0.0;
          _totalPrice = price * quantity;
          _isLoading = false;
        });
      } else {
        setState(() {
          _errorMessage = '未找到商品信息';
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = '加载商品信息异常: $e';
        _isLoading = false;
      });
    }
  }

  Future<void> _loadDefaultAddress(UserModel userModel, UserAddressModel addressModel) async {
    try {
      final client = GraphQLProvider.of(context).value;
      
      if (userModel.isLoggedIn) {
        await addressModel.loadUserAddresses(client);
        
        // 设置默认地址
        if (addressModel.addresses.isNotEmpty) {
          setState(() {
            _selectedAddress = addressModel.addresses.firstWhere(
              (address) => address.isDefaultAddress, 
              orElse: () => addressModel.addresses.first
            );
          });
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载地址失败: $e')),
        );
      }
    }
  }

  Future<void> _selectAddress(UserModel userModel, UserAddressModel addressModel) async {
    if (!userModel.isLoggedIn) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先登录')),
      );
      return;
    }

    final client = GraphQLProvider.of(context).value;
    await addressModel.loadUserAddresses(client);

    if (addressModel.addresses.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先添加收货地址')),
      );
      return;
    }

    final selectedAddress = await showDialog<UserAddress>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('选择收货地址'),
          content: SizedBox(
            width: double.maxFinite,
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: addressModel.addresses.length,
              itemBuilder: (context, index) {
                final address = addressModel.addresses[index];
                return Card(
                  child: ListTile(
                    title: Text(address.recipientName ?? ''),
                    subtitle: Text(
                      '${address.fullAddress}\n${address.phone}',
                      style: const TextStyle(fontSize: 12),
                    ),
                    trailing: address.isDefaultAddress
                        ? const Chip(
                            label: Text(
                              '默认',
                              style: TextStyle(fontSize: 12),
                            ),
                          )
                        : null,
                    onTap: () => Navigator.of(context).pop(address),
                  ),
                );
              },
            ),
          ),
        );
      },
    );

    if (selectedAddress != null) {
      setState(() {
        _selectedAddress = selectedAddress;
      });
    }
  }

  Future<void> _submitOrder(UserModel userModel, UserAddressModel addressModel, UserCartModel cartModel) async {
    final client = GraphQLProvider.of(context).value;

    // 检查必要条件
    if (!userModel.isLoggedIn) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先登录')),
      );
      return;
    }

    if (_selectedAddress == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请选择收货地址')),
      );
      return;
    }

    if (_product == null && _cartItems.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('商品信息不完整')),
      );
      return;
    }

    setState(() {
      _isCreatingOrder = true;
      _errorMessage = '';
    });

    try {
      // 准备商品数据
      List<Map<String, dynamic>> productsData = [];
      
      // 如果是单个商品（来自商品详情页）
      if (_product != null) {
        productsData.add({
          'productId': _product!.id!,
          'quantity': _quantity,
        });
      } 
      // 如果是多个商品（来自购物车）
      else if (_cartItems.isNotEmpty) {
        for (final cartItem in _cartItems) {
          final productId = cartItem.productId;
          if (productId != null) {
            productsData.add({
              'productId': productId,
              'quantity': cartItem.quantity?.toInt() ?? 1,
            });
          }
        }
      }

      // 使用GraphQL创建订单
      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchCreateOder),
          variables: {
            'receiverAddress': _selectedAddress!.fullAddress,
            'receiverName': _selectedAddress!.recipientName,
            'receiverPhone': _selectedAddress!.phone,
            'products': productsData,
          },
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('订单提交失败: ${result.exception.toString()}')),
          );
        }
      } else {
        // 订单创建成功
        final orderData = result.data!['order']['createMyOrder'];
        // 使用订单模型中的Order类
        final order = order_data.Order.fromJson(orderData);

        // 如果是来自购物车的订单，删除购物车中的商品
        if (_cartItems.isNotEmpty) {
          for (final cartItem in _cartItems) {
            final cartItemId = cartItem.id;
            if (cartItemId != null) {
              await cartModel.removeFromCart(client, cartItemId);
            }
          }
        }

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('订单提交成功')),
          );

          // 导航到订单详情页面
          Navigator.of(context).pushNamedAndRemoveUntil(
            '/order_detail',
            (route) => route.isFirst,
            arguments: order,
          );
        }
      }
    } catch (e) {
      setState(() {
        _errorMessage = '订单提交失败: $e';
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(_errorMessage)),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isCreatingOrder = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 检查是否有错误信息
    if (_errorMessage.isNotEmpty) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('确认订单'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_errorMessage),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: _loadProductFromArgs, // 重新加载
                child: const Text('重试'),
              ),
            ],
          ),
        ),
      );
    }

    // 检查是否正在加载商品信息
    if (_product == null && _cartItems.isEmpty && _isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('确认订单'),
        ),
        body: const Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    // 检查是否加载完成但没有商品信息
    if (_product == null && _cartItems.isEmpty && !_isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('确认订单'),
        ),
        body: const Center(
          child: Text('无法加载商品信息'),
        ),
      );
    }

    // 计算总价
    double totalAmount = 0.0;
    
    // 如果是单个商品（来自商品详情页）
    if (_product != null) {
      final price = double.tryParse(_product!.price ?? '0') ?? 0.0;
      totalAmount = price * _quantity;
    } 
    // 如果是多个商品（来自购物车）
    else if (_cartItems.isNotEmpty) {
      totalAmount = _totalPrice;
    }

    return Consumer3<UserModel, UserAddressModel, UserCartModel>(
      builder: (context, userModel, addressModel, cartModel, child) {
        // 当用户模型初始化完成且还未调用加载地址时，执行加载操作
        if (userModel.isLoggedIn && !_isLoadAddressesCalled) {
          _isLoadAddressesCalled = true;
          _loadDefaultAddress(userModel, addressModel);
        }

        return Scaffold(
          appBar: AppBar(
            title: const Text('确认订单'),
          ),
          body: _isCreatingOrder
              ? const Center(child: CircularProgressIndicator())
              : SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 收货地址部分
                      _buildAddressSection(userModel, addressModel),

                      // 商品信息
                      _buildProductSection(totalAmount),

                      // 支付方式
                      _buildPaymentMethodSection(),

                      // 订单备注
                      _buildRemarkSection(),

                      // 订单金额
                      _buildOrderSummary(totalAmount),

                      const SizedBox(height: 20),
                    ],
                  ),
                ),
          bottomNavigationBar: _buildBottomBar(userModel, addressModel, cartModel, totalAmount),
        );
      },
    );
  }

  Widget _buildAddressSection(UserModel userModel, UserAddressModel addressModel) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '收货地址',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                TextButton(
                  onPressed: () => _selectAddress(userModel, addressModel),
                  child: const Text('选择地址'),
                ),
              ],
            ),
            const SizedBox(height: 10),
            if (_selectedAddress != null) ...[
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _selectedAddress!.recipientName ?? '',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 5),
                        Text(
                          _selectedAddress!.fullAddress,
                          style: const TextStyle(
                            fontSize: 14,
                          ),
                        ),
                        const SizedBox(height: 5),
                        Text(
                          _selectedAddress!.phone ?? '',
                          style: const TextStyle(
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (_selectedAddress!.isDefaultAddress)
                    const Chip(
                      label: Text('默认地址'),
                      backgroundColor: Colors.blue,
                      labelStyle: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                ],
              ),
            ] else ...[
              const Center(
                child: Text(
                  '请选择收货地址',
                  style: TextStyle(
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildProductSection(double totalAmount) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '商品信息',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            // 如果是单个商品（来自商品详情页）
            if (_product != null) ...[
              _buildSingleProductItem(_product!, _quantity ?? 1),
            ]
            // 如果是多个商品（来自购物车）
            else if (_cartItems.isNotEmpty) ...[
              _buildMultipleProductItems(),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildSingleProductItem(Product product, int quantity) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: SizedBox(
              width: 80,
              height: 80,
              child: AsyncImageWidget(
                imageUrl: product.coverAddr ?? '',
                fit: BoxFit.cover,
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  product.title?.trim() ?? '未知商品',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 5),
                Text(
                  '¥${(double.tryParse(product.price?.trim() ?? '0') ?? 0.0).toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.red,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 5),
                Text(
                  '数量: $quantity',
                  style: const TextStyle(
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMultipleProductItems() {
    return Column(
      children: _cartItems
          .where((cartItem) {
            final productId = int.tryParse(cartItem.productId ?? '');
            return productId != null && _products.containsKey(productId);
          })
          .map((cartItem) {
            final productId = int.tryParse(cartItem.productId?.trim() ?? '');
            if (productId == null) {
              return Container(); // 返回空容器而不是使用continue
            }
                              
            final product = _products[productId];
            if (product == null) {
              return Container(); // 返回空容器而不是使用continue
            }
            final quantity = cartItem.quantity?.toInt() ?? 1;
            return _buildSingleProductItem(product, quantity);
          })
          .toList(),
    );
  }

  Widget _buildPaymentMethodSection() {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '支付方式',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            ListTile(
              title: const Text('钱包支付'),
              leading: Radio<String>(
                value: 'wallet',
                groupValue: _paymentMethod,
                onChanged: (value) {
                  setState(() {
                    _paymentMethod = value!;
                  });
                },
              ),
              onTap: () {
                setState(() {
                  _paymentMethod = 'wallet';
                });
              },
            ),
            ListTile(
              title: const Text('支付宝'),
              leading: Radio<String>(
                value: 'alipay',
                groupValue: _paymentMethod,
                onChanged: (value) {
                  setState(() {
                    _paymentMethod = value!;
                  });
                },
              ),
              onTap: () {
                setState(() {
                  _paymentMethod = 'alipay';
                });
              },
            ),
            ListTile(
              title: const Text('微信支付'),
              leading: Radio<String>(
                value: 'wechat',
                groupValue: _paymentMethod,
                onChanged: (value) {
                  setState(() {
                    _paymentMethod = value!;
                  });
                },
              ),
              onTap: () {
                setState(() {
                  _paymentMethod = 'wechat';
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRemarkSection() {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '订单备注',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              controller: _remarkController,
              maxLines: 3,
              decoration: const InputDecoration(
                hintText: '请输入订单备注（可选）',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOrderSummary(double totalAmount) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '订单金额',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('商品金额'),
                Text('¥${totalAmount.toStringAsFixed(2)}'),
              ],
            ),
            const SizedBox(height: 5),
            const Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '合计',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  '¥${totalAmount.toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.red,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomBar(UserModel userModel, UserAddressModel addressModel, UserCartModel cartModel, double totalAmount) {
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey,
            offset: Offset(0, -1),
            blurRadius: 2,
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '合计:',
                  style: TextStyle(
                    fontSize: 14,
                  ),
                ),
                Text(
                  '¥${totalAmount.toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.red,
                  ),
                ),
              ],
            ),
          ),
          ElevatedButton(
            onPressed: _isCreatingOrder ? null : () => _submitOrder(userModel, addressModel, cartModel),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
            ),
            child: _isCreatingOrder
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      strokeWidth: 2,
                    ),
                  )
                : const Text(
                    '提交订单',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
          ),
        ],
      ),
    );
  }
}